package com.xiaozhen.blog.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.xiaozhen.blog.annotation.LoginRequired;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.service.UserService;
import com.xiaozhen.blog.service.impl.LoginUser;
import com.xiaozhen.blog.utils.MinioUtils;
import com.xiaozhen.blog.utils.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @create 2023-04-26 13:10
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 点击修改账号信息
     *
     * @return
     */
    @LoginRequired
    @GetMapping("/setting")
    public String getSettingPage() {
        return "/setting";
    }

    /**
     * 点击上传头像
     *
     * @param headerImage
     * @param model
     * @return
     */
    @LoginRequired
    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        if (headerImage == null) {
            model.addAttribute("error", "那还没有选择图片！");
            return "/setting";
        }
        // 获取用户上传图片的文件名
        String filename = headerImage.getOriginalFilename();
        File tempFile = File.createTempFile(filename, "");
        headerImage.transferTo(tempFile);
        String filePath = tempFile.getAbsolutePath();
        // 更新当前博客首页图片的路径
        String headerUrl = MinioUtils.uploadFile("blogheader", filename, filePath);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();

        userService.updateHeader(Long.valueOf(userId), headerUrl);
        return "redirect:/";
    }

    /**
     * 点击保存昵称
     *
     * @param nickname
     * @param model
     * @return
     */
    @PostMapping("/updateNickname")
    public String updatePassword(String nickname, Model model) {
        // 获取所有的用户昵称
        List<User> userList = userService.list();

        for (User user : userList) {
            if (nickname.equals(user.getNickname())) {
                // 如果昵称相同
                model.addAttribute("nicknameMsg", "该昵称已存在！");
                return "/setting";
            }
        }

        userService.updateNickname(nickname);
        return "redirect:/";
    }

    /**
     * 点击保存密码
     *
     * @param oldPassword 用户输入的原密码
     * @param newPassword 用户输入的新密码
     * @param confirmPassword 用户输入的确认新密码
     * @param model
     * @return
     */
    @PostMapping("/updatePassword")
    public String updatePassword(String oldPassword, String newPassword, String confirmPassword, Model model) {
        // 判断用户输入的原密码与数据库中的密码是否一致
        boolean result = userService.getOldPassword(oldPassword);
        if (!result) {
            model.addAttribute("oldPasswordMsg", "原密码不正确！");
            return "/setting";
        }
        // 新密码小于 8
        if (newPassword.length() < 8) {
            model.addAttribute("newPasswordMsg", "密码的位数不能小于 8");
            return "/setting";
        }
        // 两次输入密码不一致
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "两次密码输入不一致");
            return "/setting";
        }

        // 输入的密码没有问题，更新密码
        userService.updatePassword(newPassword);
        return "redirect:/";
    }

}
